/*
import { setTimeout } from 'timers';
import { setTimeout } from 'timers';
import { constants } from 'http2';
*/
<template>
  <div class="sys-page">
    <!--增加用户表单-->
    <el-dialog :title="createDialogTitle" :visible.sync="createVisible" width='50%' :fullscreen='false'>
      <el-form :model="addForm" ref="addForm" :rules="addRules">
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="userName" label="用户名" :label-width="formLabelWidth">
                            <el-input ref="userName" v-model="addForm.userName"
                            placeholder="请输入用户用户名"></el-input>
                        </el-form-item>
                                </el-col>
                                <el-col :span="12">
                        <el-form-item prop="employerId" label="员工编号" :label-width="formLabelWidth">
                            <el-input ref="employerId" v-model="addForm.employerId"
                                      placeholder="请输入员工编号"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="password" label="登录密码" :label-width="formLabelWidth">
                            <el-input type="password" ref="password" v-model="addForm.password"
                            placeholder="请输入新增用户登录密码"></el-input>
                        </el-form-item>
                                </el-col>
                                <el-col :span="12">
                        <el-form-item prop="rePassword" label="确认密码" :label-width="formLabelWidth">
                            <el-input type="password" ref="rePassword" v-model="addForm.rePassword"
                            auto-complete="off" placeholder="请重复输入登录密码"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="realName"  label="真实姓名"
                        :label-width="formLabelWidth">
                            <el-input ref="realName"  v-model="addForm.realName" ></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item prop="idCard" label="身份证号" :label-width="formLabelWidth">
                            <el-input ref="idCard" v-model="addForm.idCard" placeholder="请输入用户身份证号"></el-input>
                        </el-form-item>
                                </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="ipEffective" label="绑定IP"
                                      :label-width="formLabelWidth">
                            <el-input ref="ipEffective"  v-model="addForm.ipEffective" ></el-input>
                        </el-form-item>
                                </el-col>
                                <el-col :span="12">
                        <el-form-item prop="identity" label="身份类型" :label-width="formLabelWidth">
                            <el-select v-model="addForm.identity" width="300px" placeholder="请选择身份类型">
                                <el-option v-for="item in userTypeOptions"
                                    :key="item.value"
                                    :label="item.text"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            <el-form-item prop="rid" label="用户角色" :label-width="roleLabelWidth">
                <el-select  v-model="addForm.rid" placeholder="请选择用户角色" @focus="focusEvent">
                <el-option v-for="item in roleTableData"
                :key="item.rid"
                :label="item.roleName"
                :value="item.rid">
                </el-option>
                </el-select>
            </el-form-item>
            <!--end-->
            </el-form>
            <div slot="footer" class="dialog-footer">
            <el-button @click="createVisible = false">取 消</el-button>
              <el-button type="primary"
                         @click.native.prevent="singleAddCommit()" >确 定</el-button>

            </div>
        </el-dialog>

    <!--修改用户信息对话框 -->
    <el-dialog :title="modifyDialogTitle" :visible.sync="modifyVisible" width='50%' :fullscreen='false'>
      <el-form :model="modifyForm" ref="modifyForm" :rules="modifyRules">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="userName" label="用户名" :label-width="formLabelWidth">
              <el-input ref="userName" v-model="modifyForm.userName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="employerId" label="员工编号" :label-width="formLabelWidth">
              <el-input ref="employerId" v-model="modifyForm.employerId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item prop="realName"  label="真实姓名" :label-width="formLabelWidth">
              <el-input ref="realName"  v-model="modifyForm.realName" ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="idCard" label="身份证号" :label-width="formLabelWidth">
              <el-input ref="idCard" v-model="modifyForm.idCard"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="ipEffective" label="绑定IP" :label-width="formLabelWidth">
              <el-input ref="ipEffective"  v-model="modifyForm.ipEffective" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="identity" label="身份类型" :label-width="formLabelWidth">
              <el-select v-model="modifyForm.identity" width="400px">
                <el-option v-for="item in userTypeOptions"
                           :key="item.value"
                           :label="item.text"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="rid" label="用户角色" :label-width="roleLabelWidth">
          <el-select  v-model="modifyForm.rid" @focus="focusEvent">
            <el-option v-for="item in roleTableData"
                       :key="item.rid"
                       :label="item.roleName"
                       :value="item.rid">
            </el-option>
          </el-select>
        </el-form-item>
        <!--end-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click.native.prevent="handleModCommit()" >确 定</el-button>
      </div>
    </el-dialog>

        <!--end add & mod-->
        <!-- 表格体 -->
            <el-table :data="tableData.body" border
                      :default-sort="{prop: 'date'}">
                <<!-- el-table-column type="index" label="序号" width="60" align="center"> -->
                </el-table-column>
                <el-table-column style="background-color:16#123456" label="数据安全" width="100" align="center">
                   <template slot-scope="scope">
                        <div v-if="scope.row.safe==false">
                            <i class="el-icon-warning"></i>
                            <span style="color:red"> 数据异常</span>
                        </div>
                        <div v-else-if="scope.row.safe==true">
                            <i class="el-icon-success"></i>
                            <span style="color:green">数据完整</span>
                        </div>
                  </template>
                </el-table-column>
                <el-table-column align="center" v-for="(item,index) in tableData.head" :prop="item.key" :formatter="cellFormatter" :label="item.name" width="200" :key="index"></el-table-column>

              <el-table-column label="操作" width="200" fixed align="center">
                    <template slot-scope="scope">
                        <el-button :disabled='scope.row.safe==false' v-if="scope.row.operation.indexOf('edit') >= 0" type="text" size="mini" icon="el-icon-edit" @click="modify(scope.$index, tableData.body)">修改</el-button>
                        <el-button :disabled='scope.row.safe==false' v-if="scope.row.operation.indexOf('delete') >= 0" type="text"  icon="el-icon-delete" size="mini" @click="delUser(scope.$index, tableData.body)"><span style="font-color:red;">删除</span></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div align="center">
              <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCount">
              </el-pagination>
          </div>
    </div>
</template>

<script>
    import {hex_md5} from "@/utils/md5";

  export default {
    inject: ['reload', 'controlObj'],
    name: 'user',
    data() {
        var validateIdentity = (rule, value, callback) =>{
            if (this.midentity === '') {
                this.validIdentity = false;
                callback(new Error('请选择身份'))
            }else {
                this.validIdentity = true;
                callback()
            }
        };
        var validateRid = (rule, value, callback) =>{
            if (this.addForm.rid === '') {
                this.validRid = false;
                callback(new Error('请选择角色'))
            }else {
                this.validRid = true;
                callback()
            }
        };
        var validateEmployerId = (rule, value, callback) =>{
            var reg = /^\d{3,}\b/;
            if (value === '') {
                this.validEmpid = false;
                callback(new Error('请输入员工编号'))
            } else if (!reg.test(value)) {
                this.validEmpid = false;
                callback(new Error('警员编号至少3位数字'))
            }
            else {
                this.HTTP.methods.apiGet("/ajax/empid/check.shtml?empId="+this.addForm.employerId).then(res =>
                {
                    if(res.code != 200){
                    this.validEmpid = false;
                        callback(new Error(res.msg))
                    }else{
                    this.validEmpid = true;
                        callback()
                    }
                })
            }
        };
        var validateIdcard = (rule, value, callback) =>{
            if (value === '') {
                this.validIdcard = false;
                callback(new Error('请输入身份证号码'))
            } else if (value.length != 18) {
                this.validIdcard = false;
                callback(new Error('身份证长度有误'))
            } else {
                this.HTTP.methods.apiGet("/ajax/idcard/check.shtml?idCard="+this.addForm.idCard)
					.then(res =>
                {
                    if(res.code != 200){
                    this.validIdcard = false;
                    callback(new Error(res.msg))
                }else{
                    this.validIdcard = true;
                    callback()
                }
            }).catch(_ => {
				   this.$message("网络超时")
				   this.loading = false;
				})
            }
        };
      var validateModifyIp = (rule, value, callback) => {
        var pattern = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
        if (this.modifyForm.ipEffective === '') {
          this.validIpeffective = false;
          callback(new Error('请输入绑定终端IP'))
        } else if (! pattern.test(this.modifyForm.ipEffective)) {
          this.validIpeffective = false;
          callback(new Error('输入IP非法'))
        } else {
          this.validIpeffective = true;
          callback()
        }
      }
        var validateIp = (rule, value, callback) => {
            var pattern = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
            if (this.addForm.ipEffective === '') {
                this.validIpeffective = false;
                callback(new Error('请输入绑定终端IP'))
            } else if (! pattern.test(this.addForm.ipEffective)) {
                this.validIpeffective = false;
                callback(new Error('输入IP非法'))
            } else {
                this.validIpeffective = true;
                callback()
            }
        }
        var validateUser = (rule, value, callback) => {
            var pattern = /^[a-zA-Z0-9]{4,}$/
            if (value === '') {
                this.validUsername = false;
                callback(new Error('用户名不能为空'))
            } else if (value.length<5) {
                this.validUsername = false;
                callback(new Error('用户名长度过短'))
            } else if (! pattern.test(value)) {
                this.validUsername = false;
                callback(new Error('用户名不允许中文'))
            } else {
                this.HTTP.methods.apiGet("/ajax/username/check.shtml?userName="+this.addForm.userName).then(res =>
                {
                    if(res.code != 200){
                    this.validUsername = false;
                        callback(new Error(res.msg))
                    }else{
                    this.validUsername = true;
                        callback()
                    }
                })
            }
        }
        var validatePass = (rule, value, callback) => {
            var pattern = /^(?=.*\d)(?=.*[a-zA-Z0-9])(?=.*[_~!@#$%^&*,./`])[\da-zA-Z0-9~_!@#$%^&*,./`]{8,}$/
            if (value === '') {
                this.validPassword = false;
                callback(new Error('请输入密码'))
            }else if(value.length <8){
                 this.validPassword = false;
                callback(new Error('长度至少8位'))
            }
            else if (! pattern.test(value)) {
                this.validPassword = false;
                callback(new Error('密码需包含英文、数字和字符'))
            } else {
                this.validPassword = true;
                callback()
            }
        };
        var validateRealname = (rule, value, callback) => {
            if (value === '') {
                this.validRealname = false;
                callback(new Error('请输入真实姓名'))
            } else {
                this.validRealname = false;
                callback()
            }
        }
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                this.validRepassword = false;
                callback(new Error('请再次输入密码'))
            } else if (value !== this.addForm.password) {
                this.validRepassword = false;
                callback(new Error('两次输入密码不一致!'))
            } else {
                this.validRepassword = false;
                callback()
            }
        };
        return {
            loading: false,
            bCount: 9,
             pageNum: 1,
            dataCount: null,
            totalCount: 0,
            pageSize: 10,
            currentPage: 1,
            start: 1,
            validUsername: false,
            validPassword: false,
            validRepassword: false,
            validIdentity: false,
            validIdcard: false,
            validRid: false,
            validRealname: false,
            validIpeffective: false,
            validEmpid: false,
            rid:'',

            formLabelWidth: '140px',
            roleLabelWidth: '140px',
            userTypeOptions: [     // 用户类型data
                { text: '警员用户', value: 1 },
                { text: '非警员用户', value: 0 }
            ],
            userRoleTypeOptions: [
                {text: '角色0', value: 0}
            ],
            ip: '',
          createDialogTitle:'用户注册',
          modifyDialogTitle: '用户修改',
          modifyVisible: false,
            addForm: {
                userName: '',
                idCard: '',
                realName: '',
                password: '',
                rePassword: '',
                employerId: '',
                ipEffective: '',
                identity: null, // required
                rid: null // required
            },
          modifyForm: {
            userName: '',
            idCard: '',
            realName: '',
            password: '',
            rePassword: '',
            employerId: '',
            ipEffective: '',
            identity: null, // required
            rid: null // requ
          },
            searchForm: {
                userName: ''
            },
            tableData: {
                head: [
                        //{key:'user'			,name:'user'},
                        {key:'userName'		,name:'用户名'},
                  {key:'employerId'	,name:'员工编号'},
                  {key:'realName'		,name:'真实姓名'},
                  {key:'roleName'		,name:'角色'},
                  {key:'ipEffective' ,name:'绑定登录IP'},
                  {key:'idCard'		,name:'身份证号'},
                  {key:'identity'		,name:'身份类别'},
                  {key:'lockType'		,name:'是否锁定'},
                        ],

                body: []
            },
            roleTableData: [],
           modifyRules: {
             ipEffective: [
               {required: true, validator: validateModifyIp, trigger: 'blur' }
             ]
           },
            addRules: {
                userName: [
                    {required: true, validator: validateUser, trigger: 'blur' }
                ],
                ipEffective: [
                    {required: true, validator: validateIp, trigger: 'blur' }
                ],
                realName: [
                    {validator: validateRealname, required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                password: [
                    {required: true,  validator: validatePass, trigger: 'blur' }
                ],
                rePassword: [
                    {required: true, validator: validatePass2, trigger: 'blur' }
                ],
                idCard: [
                    {validator: validateIdcard, required: true, trigger: 'blur' }
                ],
                rid: [
                    {validator: validateRid, required: true, message: '请至少选择一个用户所属角色类型', trigger: 'change' }
                ],
                employerId: [
                    {validator: validateEmployerId, required: true, trigger: 'blur' },
                ],
                identity: [
                    {validator: validateIdentity,  required: true, message: '请至少选择一个类型', trigger: 'change' }
                ]
            }
        }
    },
    watch:{
      createVisible(val){
        this.clearAddValidate()
      }

    },
    computed: {
      registEnable: function () {
        return !(this.validUsername && this.validPassword && this.validRepassword &&
          this.validIdentity  && this.validIdcard  && this.validRealname && this.validIpeffective &&
          this.validEmpid)
      },

      createVisible:{
        get(){

          return this.controlObj.createVisibleFlag
        },
        set(val){
          this.controlObj.createVisibleFlag = val
        }
      }
    },
    mounted() {
      // this.controlObj.createMsg = "注册用户"
      this.controlObj.createIcon = 'el-icon-circle-plus-outline'
      this.controlObj.createMsg = '新增用户'
      this.controlObj.createVisibleFlag = false
      this.getTableData()
      this.findAllRole()
    },
    methods: {
      clearAddValidate(){
        this.$refs.addForm.clearValidate()
        this.$refs.addForm.resetFields()

      },
      clearModifyValidate(){
        this.$refs.modifyForm.clearValidate()
        this.$refs.modifyForm.resetFields()
      },

         checkData(){
            this.HTTP.methods.apiGet("/user/safe.shtml").then(res =>
            {
               if(res.data == false){

                    this.$notify({
                      title: '警告',
                      message: '您访问的这张表数据不完整，记录被删除过'
                    });
               }

            }
        )
        },

         //每页显示数据量变更
        handleSizeChange: function(val) {
            this.pageSize = val;
            this.getTableData()
        },

      //页码变更
      handleCurrentChange: function(val) {
        this.pageNum = val;
        this.getTableData()
      },
      refresh(){
        this.getTableData()
        this.findAllRole()
        this.checkData()
      },
      registEnableCharge(count){
        if(count == 0){
          this.registEnable = false;
        }
      },
      tableRowClassName(row, rowIndex) {

            // if (false == row.row.safe) {
            //     return { "background-color":"orange"}
            // }
            // return '';
        },
        focusEvent(evt){
            if(0 == this.roleTableData.length) {
                this.findAllRole();
            }
        },
            getUserTitle(value) {
                var title = '未知角色'
                if(value == 'A') {
                title =  '系统管理角色'
                }else if(value == 'B') {
                    title = '安全管理角色'
                }else if(value == 'C') {
                    title = '业务处理角色'
                }else if(value == 'D') {
                    title = '安全审计角色'
                } else {

                }
                return title
            },
            //获取全部角色
            findAllRole() {
                let data = {
                    params: {}
                }
                data.params = {pageNum:1, pageSize:10000}
                this.HTTP.methods.apiGet("/role/page", data).then(res =>
                {
                    if(res.code != 200){
                        this.$message.error(res.msg)
                    }else{
                        this.roleTableData = res.data.rows
                        for( var i in this.roleTableData) {
                            this.roleTableData[i].roleTypeName = this.getUserTitle( this.roleTableData[i].roleType)
                            this.roleTableData[i].roleName = '['+  this.roleTableData[i].roleTypeName + ']' +
                              this.roleTableData[i].roleName
                        }
                    }
                })
            },
            singleAdd() {
                for (var i in this.addForm) {
                  (this.addForm)[i] = ''
                }
                this.dialogTitle = '注册用户'
                this.bCount = 9
        },
        singleAddCommit() {
            this.$refs.addForm.validate((valid) => {
            if (valid) {
                var data = {loginIp: this.ip}
                for(var prop in this.addForm){
                    if(prop == "password" || prop == "rePassword"){
                        data[prop] = hex_md5(this.addForm[prop])
                    }else{
                        data[prop] = this.addForm[prop]
                    }

                }
                data.rid = this.addForm.rid;
                data.ipEffective = this.addForm.ipEffective
                data.identity = this.addForm.identity
                this.HTTP.methods.apiPost ('/user/regist', data).then((res) => {
                if (res.code != 200) {
                    setTimeout(() => {
                    this.reload()
                    }, 1000)
                    this.$message({
                            message: res.msg,
                            type: 'error'
                    })
                } else {
                    setTimeout(() => {
                        this.reload()
                    }, 1000)
                    this.$message({
                            message: '添加成功',
                            type: 'success'
                    })
                  _g.bzeroObj(this.addForm)
                }
                })
            } else {
                return false
            }
            })
        },

      getTableData(username) {
        var url = '/user/findall'
        let data = {
          params: {}
        }
        if(username == null || username==""){ // 全量查找
          data.params = {pageNum:this.pageNum, pageSize:this.pageSize}
        }else{ // 条件查找
          data.params = {pageNum:this.pageNum, pageSize:this.pageSize,userName: username}
        }
        this.HTTP.methods.apiGet(url, data).then((res) => {
          if(res.code == 200){
            var entry = res.data
            this.tableData.body = []
            var alist = res.data.list

            for(var item in alist){
              this.transformToTableData(alist[item])
            }
            this.totalCount = res.data.total
            this.checkData()
          }else{
            this.totalCount = 0
            // $.message(res.msg)
          }
        })
      },

         cellFormatter: function (row, colum, cell) {

            if(colum.property == 'identity'){
                return row.identity == 1? '警员':'非警员'
            }else if(colum.property == 'lockType'){
                return this.getUserLockStatus(row.lockType)
            }
            return cell
        },
        lockTypeFormatter: function(row, colum, cell){
            return this.getUserLockStatus(row.lockType)
        },

        transformToTableData(user){
            var data = {
                employerId: user.employerId,
                idCard : user.idCard,
                // identity: user.identity==1?"警员":"非警员",
                identity: user.identity,
                // lockType: this.getUserLockStatus(user.lockType),
                lockType: user.lockType,
                realName: user.realName,
                roleName: user.roleName,
               rid: user.rid,
                userName: user.userName,
                ipEffective: user.ipEffective,
                safe: user.safe,
                operation:'edit,delete'
            }

            this.tableData.body.push(data)
        },

        getUserLockStatus(status){
            let res = "";
            switch(status){
                case 0:
                    res = "状态正常";
                    break;
                case 3:
                    res = "锁定(失败次数过多)";
                    break;
                case 4:
                    res = "锁定(次记录被篡改)";
                    break;
                case 5:
                    res = "锁定(账号长期未使用)";
                    break;
                default:
                    res = "锁定";
                    break;
            }
            return res;
        },


        search(){
            this.loading = true
            this.getTableData(this.searchForm.userid)
        },

        modify(index, objarr){
            this.modifyForm = _g.clone(objarr[index])
            this.modifyVisible = true
            this.clearModifyValidate()
        },

        handleModCommit(){
            this.$refs.modifyForm.validate(valid => {
              if (valid) {
                this.HTTP.methods.apiPost('/user/roleidentitymodify',this.modifyForm).then(res => {
                  if(res.code == 200){
                    this.reload()
                  }
                  this.$message({message: '修改成功', type:'success'})
                  this.dialogAddFormVisible = false
                })
              }
            })
        },

        delUser(index, arr){
          this.$confirm("确定删除 "+ arr[index]['userName'] + " ?", '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            var typ = 'error'
            this.HTTP.methods.apiPost('/user/delete',{userName: arr[index]['userName']}).then(res =>{
              if(res.code == 200){
                setTimeout(() => {this.reload()},1000)
                this.$message({message:'刪除成功', type:'success'})
                return
              }
              this.$message({message:'刪除失敗', type:'error'})
            })
          })

        }

    }
}
</script>
